package codeTop.简单;

/**
 * @author 挚爱之夕
 * @date 2021/9/22 - 09 - 22 - 16:34
 * @Description: codeTop
 * @Version: 1.0
 */
public class _001_翻转单链表 {
    /*
    LeetCode 206
     */
    public static void main(String[] args) {
        ListNode l5 = new ListNode(5,null);
        ListNode l4 = new ListNode(4,l5);
        ListNode l3 = new ListNode(3,l4);
        ListNode l2 = new ListNode(2,l3);
        ListNode l1 = new ListNode(1,l2);
        printList(l1);
        System.out.println();
        ListNode res = reverseList(l1);
        printList(res);
    }
    private static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
    private static void printList(ListNode head){
        while(head!=null){
            System.out.print(head.val+"->");
            head = head.next;
        }
        System.out.print("null");
    }

    //迭代
    private static ListNode reverseList(ListNode head) {
        ListNode p = head;
        ListNode pre = null;
        while(p != null){
            ListNode next = p.next;
            p.next = pre;
            pre = p;
            p = next;
        }
        return pre;
    }

    //递归
    private static ListNode reverseList1(ListNode head) {
        if(head == null||head.next==null)
            return head;
        ListNode newHead = reverseList1(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }
}
/*
ListNode pre = null;
        ListNode cur = head;
        while(cur!=null){
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
 */
